package core

import (
	"animal/octopus/common"
	"animal/octopus/orm"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func GetEventList(param common.GetEventListParam) (*common.GetEventListRsp, error) {
	events, totalCount, err := orm.GetEventList(nil, param)
	if err != nil {
		log.Error("get event list failed")
		return nil, err
	}

	var rsp common.GetEventListRsp
	for _, event := range events {
		rsp.Events = append(rsp.Events, common.EventInfo{
			EventID:      event.ID,
			RootModuleID: event.RootModuleID,
			ModuleID:     event.ModuleID,
			ModuleName:   event.ModuleName,
			EventType:    event.Type,
			Attribute:    event.Attribute,
			CreateTime:   common.TimeFormat(event.CreatedAt),
		})
	}

	rsp.TotalSize = totalCount
	rsp.PageIndex = param.PageIndex
	rsp.PageSize = param.PageSize

	return &rsp, nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func DeleteEvent(param common.DeleteEventParam) error {
	return orm.DeleteEvent(nil, param)
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func BatchDeleteEvent(param common.BatchDeleteEventParam) error {
	if err := common.DB(nil).Transaction(func(tx *gorm.DB) error {
		for _, event := range param.Events {
			if err := orm.DeleteEvent(nil, common.DeleteEventParam{
				EventID: event,
			}); err != nil {
				log.WithField("ID", event).Error("delete event failed")
				return err
			}
		}
		return nil
	}); err != nil {
		log.Error("batch delete events failed")
		return err
	}
	return nil
}
